import { reqBatchRemoveHospitals, reqGetHospitalSetList, reqRemoveHospital } from '@/api/hospital/hospitalSet'
import { HospitalSetItem, HospitalSetList, SearchParams } from '@/api/hospital/model/hospitalSetTypes'
import { Button, Card, Form, Input, message, Modal, Space, Table, Tooltip } from 'antd'
import { EditOutlined, DeleteOutlined, SearchOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/lib/table'
import { Key, useEffect, useState } from 'react'
import { useNavigate } from 'react-router-dom';

export default function HospitalSet() {
    const [hospitalSetList, setHospitalSetList] = useState<HospitalSetList>([])
    const [current, setCurrent] = useState<number>(1)
    const [pageSize, setPageSize] = useState<number>(5)
    const [total, setTotal] = useState<number>()
    const [selectedRowKeys, setSelectedRowKeys] = useState<Key[]>([]);
    const [lastHosname, setLastHosname] = useState<string>();
    const [lastHoscode, setLastHoscode] = useState<string>();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState<boolean>(false);
    const navigate = useNavigate()


    //异步请求获取医院列表数据
    const getHospitalSetList = async (current: number, pageSize: number, hosname?: string, hoscode?: string) => {
        setLoading(true);
        let res = await reqGetHospitalSetList({
            page: current,
            limit: pageSize,
            hoscode,
            hosname,
        })
        //设置医院的最新列表
        setHospitalSetList(res.records)
        setCurrent(current)
        setPageSize(pageSize)
        //设置total
        setTotal(res.total)
        setLoading(false);
    }

    //componentDidMount  
    useEffect(() => {
        getHospitalSetList(current, pageSize)
    }, [])

    const onSelectChange = (newSelectedRowKeys: Key[]) => {
        console.log('selectedRowKeys changed: ', newSelectedRowKeys);
        setSelectedRowKeys(newSelectedRowKeys);
    };

    const rowSelection = {
        selectedRowKeys,
        onChange: onSelectChange,
    };

    //提交表单
    const onFinish = ({ hosname, hoscode }: SearchParams) => {
        setLastHosname(hosname);
        setLastHoscode(hoscode);

        getHospitalSetList(current, pageSize, hosname, hoscode)
    }

    //清空
    const reset = () => {
        setCurrent(1)
        setPageSize(5)
        setLastHosname("")
        setLastHoscode("")

        getHospitalSetList(1, 5, "", "");

        form.resetFields()
    }

    //showBatchRemoveModal
    const showBatchRemoveModal = () => {
        Modal.confirm({
            title: `您确认要删除所有选中的数据吗？`,
            async onOk() {
                await reqBatchRemoveHospitals(selectedRowKeys);
                message.success("批量删除成功");
                // 清空选中的数据（这样按钮就会禁用了）
                setSelectedRowKeys([]);
                //   // 重新请求最新的数据展示
                getHospitalSetList(current, pageSize, lastHosname, lastHoscode);
            },
        });
    }

    //新增
    const goAddHospital = () => {
        navigate("/syt/hospital/hospitalSet/add")
    }

    //编辑
    const editHospital = (row: HospitalSetItem) => {
        navigate("/syt/hospital/hospitalSet/edit", { state: row })
    }

    //删除
    const deleteHospital = (hosname: string, id: number) => {
        Modal.confirm({
            title: `您确认要删除${hosname}这条数据吗?`,
            async onOk() {
                await reqRemoveHospital(id);
                message.success("删除成功!");
                // 清空选中的数据（这样按钮就会禁用了）
                setSelectedRowKeys([]);
                //   // 重新请求最新的数据展示
                getHospitalSetList(current, pageSize, lastHosname, lastHoscode);
            }
        })
    }

    const columns: ColumnsType<any> = [
        {
            title: '序号',
            render: (row, record, index) => index + 1,
            align: "center"
        },
        {
            title: '医院名称',
            dataIndex: "hosname",
            align: "center"
        },
        {
            title: '医院编号',
            dataIndex: "hoscode",
            align: "center"
        },
        {
            title: 'api基础路径',
            dataIndex: "apiUrl",
            align: "center"
        },
        {
            title: '签名',
            dataIndex: "signKey",
            align: "center"
        },
        {
            title: '联系人姓名',
            dataIndex: "contactsName",
            align: "center"
        },
        {
            title: '联系人手机',
            dataIndex: "contactsPhone",
            align: "center"
        },
        {
            title: '操作',
            align: "center",
            render: (row) => {
                return (
                    <>
                        <Space>
                            <Tooltip placement="top" title="修改医院">
                                <Button type="primary" onClick={() => {
                                    editHospital(row)
                                }}><EditOutlined /></Button>
                            </Tooltip>
                            <Tooltip placement="top" title="删除医院">
                                <Button type="primary" danger onClick={() => {
                                    deleteHospital(row.hosname, row.id)
                                }}> <DeleteOutlined /></Button>
                            </Tooltip>
                        </Space>
                    </>
                )
            }
        }
    ]

    return (
        <Card>
            <Form
                layout="inline"
                onFinish={onFinish}
                form={form}
            >
                <Form.Item name='hosname'>
                    <Input placeholder='医院名称'></Input>
                </Form.Item>
                <Form.Item name='hoscode'>
                    <Input placeholder='医院编号'></Input>
                </Form.Item>
                <Form.Item>
                    <Button icon={<SearchOutlined />} type='primary' htmlType="submit">查询</Button>
                </Form.Item>
                <Form.Item>
                    <Button onClick={reset}>清空</Button>
                </Form.Item>
            </Form>
            <div className='mt'>
                <Space>
                    <Button type="primary" onClick={goAddHospital}>添加</Button>
                    <Button type="primary" danger disabled={!selectedRowKeys.length} onClick={showBatchRemoveModal}>批量删除</Button>
                </Space>
            </div>
            <Table
                className='mt'
                columns={columns}
                dataSource={hospitalSetList}
                rowSelection={rowSelection}
                rowKey="id"
                loading={loading}
                pagination={{
                    current,
                    pageSize,
                    total,
                    pageSizeOptions: [5, 10, 15, 20],
                    showSizeChanger: true,
                    showQuickJumper: true,
                    showTotal: (total) => `总共${total}`,
                    onChange: (current, pageSize) => {
                        // 发送请求，请求新的数据
                        getHospitalSetList(current, pageSize, lastHosname, lastHoscode);
                    },
                }}
            >
            </Table>
        </Card>
    )
}
